<template>
    <div class="content">



        <div class="info-box">

            <div class="title">
                <div style="margin-left:15px ;">基本信息</div>
            </div>

            <div class="info" style="margin-top: 24px;">


                <div class="line1">

                    <div>商品图片：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
                    <!-- <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload> -->


                    <el-upload action="https://upload-z1.qiniup.com" list-type="picture-card" :data="QiniuData" :limit="5"
                        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-error="uploadError"
                        :before-upload="beforeUpload" accept="image/jpeg, image/jpg, image/png" :file-list="fileList"
                        :on-success="uploadFiles" :on-exceed="onExceed" style="margin-left: 10px; margin-top: 10px;">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>


                </div>
                <div class="font" style="margin-top: 10px; margin-left: 100px; font-size: 10px; color: #999;">建议尺寸：800*800;
                </div>

                <div class="line2" style="margin-top: 20px;">
                    <div class="line2">商品名称：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
                    <el-input placeholder="请输入商品名称" v-model="currentRow.name" style="width: 260px;"
                        class="line2"></el-input>
                </div>


                <div style="margin-top: 20px;">
                    <div class="line2">商品类目：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
                    <div class="line2">
                        <!-- <span class="demonstration">默认 click 触发子菜单</span> -->
                        <el-cascader v-model="sortValue" prop-name="name" :options="categoryTree" :props="optionProps"
                            @change="sortChange" placeholder="请选择类目" style="width: 260px"></el-cascader>
                    </div>
                </div>

            </div>



            <div class="title" style="margin-top: 30px;">
                <div style="margin-left:15px;">属性/价格</div>
            </div>

            <div class="info">

                <div class="line2" style="margin-top: 20px;">
                    <div class="line2">前端显示价格：</div>
                    <el-input type="number" step="0.01" placeholder="请输入前端显示价格" v-model="currentRow.original_price"
                        style="width: 260px;" class="line2"></el-input>
                </div>

                <div class="line2" style="margin-top: 20px;">
                    <div class="line2">会员结算价格：</div>
                    <el-input type="number" step="0.01" placeholder="请输入会员结算价格" v-model="currentRow.price"
                        style="width: 260px;" class="line2"></el-input>
                </div>



                <div class="line2" style="margin-top: 20px;">
                    <div class="line2">
                        毛重：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
                    <el-input placeholder="请输入毛重" v-model="currentRow.gross_weight" style="width: 260px;"
                        class="line2"></el-input> <template>克</template>
                </div>


                <div class="line2" style="margin-top: 20px;">
                    <div class="line2">商品规格：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
                    <el-button type="primary" @click="addSpec">+添加规格</el-button>
                </div>


                <el-radio-group v-model="currentRow.specification" style="margin-top: 15px; margin-left: 93px;">
                    <el-radio v-for="spec in specifications" :label="spec.id" :key="spec.id">{{ spec.name }}</el-radio>
                </el-radio-group>

            </div>

            <div class="title" style="margin-top: 20px;">
                <div style="margin-left:15px;">运费其他</div>
            </div>

            <div class="info">
                <div class="line2" style="margin-top: 20px;">
                    <div class="line2">运费设置：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
                    <el-select v-model="currentRow.express_template" placeholder="请选择">
                        <el-option v-for="item in expressTemplates" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                    <!-- <el-button type="primary" @click="addExpress">+添加快递模板</el-button> -->
                    <router-link to="/express_template">go</router-link>
                </div>

                <div class="line2" style="margin-top: 20px;">
                    <div class="line2">其他设置：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
                    <el-checkbox v-model="isIndexShow" class="line2">首页推荐</el-checkbox>

                </div>

            </div>


            <div class="title">
                <div style="margin-left:15px ;">商品详情</div>
            </div>
            <goodsEditor @changeTxt="changeTxt" :qiNiuToken="QiniuData.token"
                style="margin-left: 15px; margin-top: 15px; margin-right: 15px;" />


            <!-- <el-input v-model="goodDetails" placeholder="请输入内容" type="textarea" :autosize="autosize"
                style="margin-left: 30px; margin-top: 12px;"></el-input> -->

            <div style="width: 100%; display: flex; flex-direction: column; align-items: center;">
                <el-button style="align-items: center; width: 108px;margin: 18px 0px 22px 0px;" type="primary"
                    @click="commitGood">提交商品</el-button>
            </div>







        </div>


        <el-dialog title="添加规格" :visible.sync="addFormSpec" center :show-close="false">
            <el-form :model="form">
                <el-form-item label="规格文本:" label-width="120px">
                    <el-input v-model="form.specText" placeholder="请输入规格文本"></el-input>
                </el-form-item>
                <el-form-item label="规格值:" label-width="120px">
                    <el-input v-model="form.specValue" placeholder="请输入规格值" type="number" step="0.01"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="addFormSpec = false">取消</el-button>
                <el-button type="primary" @click="confirmDialogClick">确定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { get, post } from '@/utils/request';
import { url } from '@/utils/url';
import goodsEditor from "./goodsEditor";
import "@wangeditor/editor/dist/css/style.css"//

export default {
    components: { goodsEditor },
    data() {
        return {

            html: "",
            optionProps: {
                value: "id",
                label: "name",
                children: "children",
            },
            currentRow: {
                name: '',
                images: [],
                categoryOneAndTwo: '',
                category_one: '',
                category_two: '',
                original_price: '',
                price: '',
                gross_weight: '',
                specification: '',
                express_template: ''
            },
            fileList: [],
            isIndexShow: false,
            sortValue: [],
            expressTemplates: [],
            QiniuData: {    //这里是直接绑定data的值
                key: "", //图片名字处理
                token: "", //七牛云token
                data: {},
                bucket: "fyjyg"
            },
            form: {
                specText: "",
                specValue: "",
            },
            addFormSpec: false,
            imageUrl: '',
            dialogImageUrl: '',
            dialogVisible: false,
            file_list: [],

            categoryTree: [{
                value: 'zhinan',
                label: '指南',
                children: [{
                    value: 'shejiyuanze',
                    label: '设计原则',
                    children: [{
                        value: 'yizhi',
                        label: '一致',

                        children: [{
                            value: 'xiaoyizhi',
                            label: '小一直',
                        },
                        {
                            value: 'wanquanyizhi',
                            label: '完全一致',
                        }
                        ]


                    }, {
                        value: 'fankui',
                        label: '反馈'
                    }, {
                        value: 'xiaolv',
                        label: '效率'
                    }, {
                        value: 'kekong',
                        label: '可控'
                    }]
                }, {
                    value: 'daohang',
                    label: '导航',
                    children: [{
                        value: 'cexiangdaohang',
                        label: '侧向导航'
                    }, {
                        value: 'dingbudaohang',
                        label: '顶部导航'
                    }]
                }]
            }, {
                value: 'zujian',
                label: '组件',
                children: [{
                    value: 'basic',
                    label: 'Basic',
                    children: [{
                        value: 'layout',
                        label: 'Layout 布局'
                    }, {
                        value: 'color',
                        label: 'Color 色彩'
                    }, {
                        value: 'typography',
                        label: 'Typography 字体'
                    }, {
                        value: 'icon',
                        label: 'Icon 图标'
                    }, {
                        value: 'button',
                        label: 'Button 按钮'
                    }]
                }, {
                    value: 'form',
                    label: 'Form',
                    children: [{
                        value: 'radio',
                        label: 'Radio 单选框'
                    }, {
                        value: 'checkbox',
                        label: 'Checkbox 多选框'
                    }, {
                        value: 'input',
                        label: 'Input 输入框'
                    }, {
                        value: 'input-number',
                        label: 'InputNumber 计数器'
                    }, {
                        value: 'select',
                        label: 'Select 选择器'
                    }, {
                        value: 'cascader',
                        label: 'Cascader 级联选择器'
                    }, {
                        value: 'switch',
                        label: 'Switch 开关'
                    }, {
                        value: 'slider',
                        label: 'Slider 滑块'
                    }, {
                        value: 'time-picker',
                        label: 'TimePicker 时间选择器'
                    }, {
                        value: 'date-picker',
                        label: 'DatePicker 日期选择器'
                    }, {
                        value: 'datetime-picker',
                        label: 'DateTimePicker 日期时间选择器'
                    }, {
                        value: 'upload',
                        label: 'Upload 上传'
                    }, {
                        value: 'rate',
                        label: 'Rate 评分'
                    }, {
                        value: 'form',
                        label: 'Form 表单'
                    }]
                }, {
                    value: 'data',
                    label: 'Data',
                    children: [{
                        value: 'table',
                        label: 'Table 表格'
                    }, {
                        value: 'tag',
                        label: 'Tag 标签'
                    }, {
                        value: 'progress',
                        label: 'Progress 进度条'
                    }, {
                        value: 'tree',
                        label: 'Tree 树形控件'
                    }, {
                        value: 'pagination',
                        label: 'Pagination 分页'
                    }, {
                        value: 'badge',
                        label: 'Badge 标记'
                    }]
                }, {
                    value: 'notice',
                    label: 'Notice',
                    children: [{
                        value: 'alert',
                        label: 'Alert 警告'
                    }, {
                        value: 'loading',
                        label: 'Loading 加载'
                    }, {
                        value: 'message',
                        label: 'Message 消息提示'
                    }, {
                        value: 'message-box',
                        label: 'MessageBox 弹框'
                    }, {
                        value: 'notification',
                        label: 'Notification 通知'
                    }]
                }, {
                    value: 'navigation',
                    label: 'Navigation',
                    children: [{
                        value: 'menu',
                        label: 'NavMenu 导航菜单'
                    }, {
                        value: 'tabs',
                        label: 'Tabs 标签页'
                    }, {
                        value: 'breadcrumb',
                        label: 'Breadcrumb 面包屑'
                    }, {
                        value: 'dropdown',
                        label: 'Dropdown 下拉菜单'
                    }, {
                        value: 'steps',
                        label: 'Steps 步骤条'
                    }]
                }, {
                    value: 'others',
                    label: 'Others',
                    children: [{
                        value: 'dialog',
                        label: 'Dialog 对话框'
                    }, {
                        value: 'tooltip',
                        label: 'Tooltip 文字提示'
                    }, {
                        value: 'popover',
                        label: 'Popover 弹出框'
                    }, {
                        value: 'card',
                        label: 'Card 卡片'
                    }, {
                        value: 'carousel',
                        label: 'Carousel 走马灯'
                    }, {
                        value: 'collapse',
                        label: 'Collapse 折叠面板'
                    }]
                }]
            }, {
                value: 'ziyuan',
                label: '资源',
                children: [{
                    value: 'axure',
                    label: 'Axure Components'
                }, {
                    value: 'sketch',
                    label: 'Sketch Templates'
                }, {
                    value: 'jiaohu',
                    label: '组件交互文档'
                }]
            }],
            specifications: ['1/瓶', '1/盒', '1/桶', '1/箱'],
            templates: [{
                value: '选项1',
                label: '黄金糕'
            }, {
                value: '选项2',
                label: '双皮奶'
            }, {
                value: '选项3',
                label: '蚵仔煎'
            }, {
                value: '选项4',
                label: '龙须面'
            }, {
                value: '选项5',
                label: '北京烤鸭'
            }],
            templateName: '',
            others: ['首页推荐'],
            checkedOthers: [],
            autosize: {
                minRows: 10,
            },
            goodDetails: ''
        }
    },
    computed: {

    },
    mounted() {
        this.getSpecs();
        this.getCategory();
        this.getExpressTemplates();
        this.getQiNiuToken();

    },

    methods: {
        onCreated(editor) {
            this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
            this.$nextTick(() => {
                //一定要用 this.$nextTick包裹起来，等editor实例创建好之后才能获取到toolbar实例
                this.toolbar = DomEditor.getToolbar(this.editor);
                this.toolbar.config.insertKeys = {
                    index: 4, // 插入的位置，基于当前的 toolbarKeys
                    keys: ['emotion'],
                };
            });
            this.toolbarConfig.toolbarKeys = [
                // 菜单 key或者组的key
                'headerSelect',

                // 注意分割线也算一个菜单
                '|',

                // 菜单 key
                'bold',
                'italic',
                'color',
                'justifyLeft',
                'justifyRight',
                'justifyCenter'


                // 继续配置其他菜单...
            ]

        },

        changeTxt(editDataHtml) {
            this.html = editDataHtml
            console.log("changeTxt：" + editDataHtml)
        },

        //获取所有快递模板
        getExpressTemplates() {
            get(url.expressTemplates, {
                page: 1,
                per_page: 1000,
            }).then((response) => {
                this.expressTemplates = response.data.data;
            })
                .catch((error) => {
                    console.error(error); // 在这里处理错误
                });
        },
        //获取规格
        getCategory() {
            get(url.categoryTree, {
                name: '',
                page: 1,
                per_page: 1000
            }).then(response => {
                let data = response.data
                this.categoryTree = data

            }).catch(error => {
                console.error(error); // 在这里处理错误  
            });
        },


        sortChange(params) {
            console.log("当前分类的sort是=====>" + params)
            console.log("当前分类的sortValue是=====>" + this.sortValue)
            this.currentRow.category_one = 0;//重置
            this.currentRow.category_two = 0;//重置
            params.forEach((option, index) => {
                console.log(`当前分类的sort是=====Level ${index}: ${option}`); // 输出每个级联的值和层级  
                if (index == 0) {
                    this.currentRow.category_one = option
                } else if (index == 1) {
                    this.currentRow.category_two = option
                }
            });
        },


        //获取规格
        getSpecs() {
            get(url.specifications, {
                name: '',
                page: 1,
                per_page: 1000
            }).then(response => {
                let data = response.data
                this.specifications = data.data

            }).catch(error => {
                console.error(error); // 在这里处理错误  
            });
        },



        addExpress() {
            console.log('点击了跳转运费模板')
            this.$router.push({ path: '/express_template' })
        },



        //获取七牛云token 
        getQiNiuToken() {
            get(url.qiniuToken, {
            }).then(response => {
                this.QiniuData.token = response.data.uptoken
            }).catch(error => {

            });
        },

        beforeUpload(file) {
            // console.log(file);
            let suffix = file.name;
            // let key = "upload/009/" + encodeURI(`${suffix}`);
            //   let key = encodeURI(`${suffix}`)
            let key = `image/public/goodsPic/pic_${new Date().getTime()}_${file.name}`

            // let key = new Date () + Math.floor(Math.random()*100) + encodeURI(`${suffix}`)
            this.QiniuData.key = key;
            return this.QiniuData;
        },

        uploadError(error) {
            console.log('uploadError执行了 上传图片失败的原因： ' + JSON.stringify(error))
        },

        uploadFiles(res, file, fileList) {
            console.log('上传成功：' + JSON.stringify(res.key))
            console.log('fileList:==========' + JSON.stringify(fileList))
            let image = res.key
            this.currentRow.images.push(image)
            console.log("现在currentRow.images 的值 为：" + JSON.stringify(this.currentRow.images))
        },



        commitGood() {

            console.log("当前选择的" + JSON.stringify(this.currentRow))
            console.log("当前 this.html" + this.html)
            let row = this.currentRow

            if (row.name == '') {
                this.$message({
                    message: '请输入商品名称'
                })
                return
            }
            if (row.images == null || row.images.length == 0) {
                this.$message('请上传商品图片')
                return
            }

            if (row.category_one == '') {
                this.$message('请选择商品分类')
                return
            }

            if (row.original_price == '') {
                this.$message("请输入前端展示价格")
                return
            }

            if (row.price == '') {
                this.$message("请输入会员价格")
                return
            }

            if (row.gross_weight == '') {
                this.$message("请输入毛重")
                return
            }



            if (row.specification == '') {
                this.$message("请选择商品规格")
                return
            }


            if (row.express_template == '') {
                this.$message("请选择快递模板")
                return
            }


            if (this.html == '<p><br></p>') {
                this.$message("请编辑商品内容")
                return
            }



            post(url.adminGoods, {
                name: row.name,
                images: row.images.join(','),
                category_one: row.category_one,
                category_two: row.category_two,
                original_price: row.original_price,
                price: row.price,
                gross_weight: row.gross_weight,
                content: this.html,
                specification: row.specification,
                express_template: row.express_template,
                recommend: this.isIndexShow ? '1' : '0'
                


            }).then(response => {
                console.log(JSON.stringify(response))
                if (response == null || response == undefined) {
                    return
                }
                this.$router.push({ path: '/goods' })


            }).catch(error => {
                console.error(error); // 在这里处理错误  
            })
        },
        handleRemove(file, fileList) {
            console.log("file====" + JSON.stringify(file));
            console.log("fileList===:" + JSON.stringify(fileList));
            this.file_list = fileList
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },


        onExceed() {
            // this.$alert("sssssssssssssssssssss", "温馨提示", {
            //     confirmButtonText: "确定",
            // }).then(() => {
            //        console.log('woshinidie')
            // });

            this.$alert('超出图片数量限制', "温馨提示", {
                confirmButtonText: "确定",
                callback: action => {
                    console.log('quxiaole')
                }
            });

        },
        handleChange(row) {
            console.log(Json.stringify(row))
        },
        addSpec() {
            this.addFormSpec = true
        },
        //点击添加规格按钮
        confirmDialogClick() {
            if (this.form.specText == "") {
                this.$message({
                    message: '请填写规格文本',
                    type: 'warning'
                });
                return
            }

            if (this.form.specValue == "") {
                this.$message({
                    message: '请填写规格值',
                    type: 'warning'
                });
                return
            }
            this.addSpecPost()
        },
        addSpecPost() {
            post(url.addSpecification, {
                name: this.form.specText,
                value: this.form.specValue,
            }).then(response => {
                this.addFormSpec = false
                this.getSpecs()


            }).catch(error => {
                console.error(error); // 在这里处理错误  
            });
        }

    },
}
</script>

<style lang="scss">
.content {
    overflow: auto;
    background: white;
    display: flex;
    flex-direction: column;
    border-radius: 5px;
    border: solid 6px #F5F5F5;

    .title {
        align-items: center;
        margin-top: 10px;
        display: flex;
        font-weight: bolder;
        color: #333;
        height: 30px;
        margin-right: 20px;
        margin-left: 20px;
        background-color: #EEEEEE;
    }

    .info-box {
        flex-direction: column;
        width: 100%;
        height: auto;




        .info {

            flex-direction: column;
            margin-left: 75px;
            width: 100%;
            display: flex;

            .line1 {
                display: flex;
                align-items: center;
                font-size: 12px;
                color: #333;

            }

            .line2 {
                font-size: 12px;
                display: inline-block;
                margin-right: 10px;
                /* 根据需要调整间距 */
                /* 根据需要调整内边距 */

            }


        }



        .price-shu-xing {

            flex-direction: column;
            margin-top: 35px;
            margin-left: 75px;
            width: 100%;
            display: flex;

            .line1 {
                display: flex;
                align-items: center;
                font-size: 12px;
                color: #333;

            }

            .line2 {
                display: inline-block;
                margin-right: 10px;
                font-size: 12px;
                color: #333;
                /* 根据需要调整间距 */
                /* 根据需要调整内边距 */

            }


        }

        .good-detail {
            margin-top: 12px;
            margin-left: 30px;
            height: 240px;
            border: 1px solid #ccc;
        }

    }
}
</style>